<template>
  <div>
    <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
      <el-row>
        <el-col class="singleDatePicker">
          <el-form-item label="有无项目" size="small">
            <el-switch
              v-model="teamRow.isExist"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value=1
              :inactive-value=0
            >
            </el-switch>
          </el-form-item>
          <el-form-item prop="tenderName" v-if="teamRow.isExist" label="投标项目" size="small">
            <el-autocomplete
              v-model="teamRow.tenderName"
              :fetch-suggestions="querySearchProject"
              @select="handleSelectProject"
              placeholder="请输入内容"
              style="width: 190px;"
            >
            </el-autocomplete>
          </el-form-item>
          <el-form-item v-if="teamRow.teamName && teamRow.isExist" label="所属团队" size="small">
            {{teamRow.teamName}}
          </el-form-item>
          <el-form-item v-if="teamRow.partyA && teamRow.isExist" label="招标方" size="small">
            {{teamRow.partyA}}
          </el-form-item>
          <div v-if="!teamRow.isExist">
            <el-form-item label="所属团队" size="small">
              <!--<el-autocomplete-->
              <!--v-model="teamRow.teamName"-->
              <!--:fetch-suggestions="querySearchTeam"-->
              <!--@select="handleSelectTeam"-->
              <!--placeholder="请输入内容"-->
              <!--&gt;-->
              <!--</el-autocomplete>-->
              <el-input type="text" v-model="teamRow.teamName" disabled></el-input>
            </el-form-item>
          </div>

          <el-form-item prop="billAmount" label="收款金额" size="small">
            <el-input type="number" v-model.number="teamRow.billAmount">
              <span slot="suffix">万元</span>
            </el-input>
          </el-form-item>
          <el-form-item prop="billTime" label="收款时间" size="small">
            <el-date-picker
              v-model="teamRow.billTime"
              type="date"
              value-format="timestamp"
              placeholder="选择日期"
              style="width: 190px;"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="receivingUnit" label="收款单位" size="small">
            <el-select v-model="teamRow.receivingUnit" placeholder="请选择" @change="receivingUnitChange">
              <el-option
                v-for="item in global.billUnitList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注说明" size="small">
        <el-input type="textarea" v-model="teamRow.remark"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
      <el-button size="small" @click="$emit('closeDialog')">取消</el-button>
    </div>
  </div>
</template>

<script>
  import {
    addTenderCompensation,
    deleteTenderCompensation,
    getTenderCompensationList,
    selectProjectName,
    selectTeam,
    selectTenderCompensation,
    updateTenderCompensation,
    selectOperator,
    updateCost
  } from '@/api/tendercompensation'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const time = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const isExist = function(row, column) {
    return row.isExist ? '有' : '无'
  }

  const receivingUnit = function(row, column) {
    if (row.receivingUnit) {
      let obj = {}
      obj = global.billUnitList.find((item) => {
        return item.value === row.receivingUnit // 筛选出匹配数据
      })
      return obj.label
    }
  }
  export default {
    components: {
      myTable,
      AreaSelect
    },
    props: ['outerVisible', 'balanceId'],
    data() {
      const validateCostAmount = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入支出金额!'))
        } else if (value > this.billRow.balance) {
          callback(new Error('请输入正确金额!'))
        } else {
          callback()
        }
      }
      const validateBillAmount = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入收款金额!'))
        } else if (value < this.billAmount - this.teamRow.balance) {
          callback(new Error('收款金额须大于支出金额!'))
        } else {
          callback()
        }
      }
      return {
        colConfigs: [
          { prop: 'isExist', label: '有无项目', width: '80', fixed: true, formatter: isExist },
          { prop: 'tenderName', label: '投标项目名称', minWidth: '35%', fixed: true },
          { prop: 'teamName', label: '团队名称', width: '100' },
          { prop: 'balance', label: '剩余余额(万元)', width: '100' },
          { prop: 'billAmount', label: '收款金额(万元)', width: '100' },
          { prop: 'partyA', label: '招标方', minWidth: '20%' },
          { prop: 'billTime', label: '收款时间', width: '100', component: time },
          { prop: 'receivingUnit', label: '收款单位', width: '100', formatter: receivingUnit },
          { prop: 'remark', label: '备注说明', minWidth: '20%' },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        costTypes: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增投标补偿金',
        marginTitle: '',
        marginType: 1,
        dialogType: 1,
        teamRow: {},
        teamRowClear: {},
        billRow: {},
        margin: {},
        marginClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerBillVisible: false,
        pca: pca,
        rules: {
          tenderName: [
            { required: true, message: '请输入项目名称', trigger: 'change' }
          ],
          teamName: [
            { required: true, message: '请输入团队名称', trigger: 'change' }
          ],
          partyA: [
            { required: true, message: '请输入招标方', trigger: 'change' }
          ],
          billTime: [
            { required: true, message: '请选择收款时间', trigger: 'change' }
          ],
          billAmount: [
            { required: true, trigger: 'change', validator: validateBillAmount }
          ],
          receivingUnit: [
            { required: true, message: '请选择收款单位', trigger: 'change' }
          ]
        },
        billRules: {
          costTime: [
            { required: true, message: '请选择支出时间', trigger: 'change' }
          ],
          costAmount: [
            { required: true, trigger: 'change', validator: validateCostAmount }
          ],
          payer: [
            { required: true, message: '请输入收款人', trigger: 'change' }
          ]
        },
        visible: false,
        visibleType: 0,
        billAmount: 0
      }
    },
    created() {
      // this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      // this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      teamId() {
        return this.$store.state.user.teamId
      },
      teamName() {
        return this.$store.state.user.teamName
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.searchFormList.billType = 1
        this.listLoading = true
        getTenderCompensationList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      provinceChange() {
        this.searchForm.cityId = ''
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
      },
      editTeam(billId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改投标补偿金'
        this.dialogType = 0
        if (this.$refs.payCertificate) {
          this.$refs.payCertificate.value = ''
        }
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          billId: billId
        }
        selectTenderCompensation(params).then(response => {
          this.teamRow = response.responseBody
          this.teamRow.tenderId = this.teamRow.projectId
          this.billAmount = this.teamRow.billAmount
        })
      },
      editBill(billId) {
        if (this.$refs['billRow']) {
          this.$refs['billRow'].resetFields()
        }
        this.outerBillVisible = true
        const params = {
          billId: billId
        }
        selectTenderCompensation(params).then(response => {
          this.billRow = response.responseBody
          delete this.billRow.costAmount
          delete this.billRow.costTime
          delete this.billRow.payer
        })
      },
      submitForm(formName) {
        const params = {
          isExist: this.teamRow.isExist,
          teamId: this.teamRow.teamId,
          teamName: this.teamRow.teamName,
          partyA: this.teamRow.partyA,
          billAmount: this.teamRow.billAmount,
          billTime: this.teamRow.billTime,
          receivingUnit: this.teamRow.receivingUnit,
          receivingUnitName: this.teamRow.receivingUnitName,
          remark: this.teamRow.remark ? this.teamRow.remark : ''
        }
        if (this.teamRow.isExist) {
          params.projectId = this.teamRow.tenderId
          params.tenderName = this.teamRow.tenderName
          if (!this.teamRow.tenderId) {
            this.$message({
              message: '该项目不存在',
              type: 'warning'
            })
            return
          }
        }
        if (!this.dialogType) {
          params.billId = this.teamRow.billId
          params.dateCreated = this.teamRow.dateCreated
        }
        // 判断balanceId 银行余额登记 与原页面不同
        if (this.balanceId) {
          params.balanceId = this.balanceId
        }

        if (this.teamRow.teamId) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.dialogType) {
                addTenderCompensation(params).then(response => {
                  this.addTeam()
                })
              } else {
                updateTenderCompensation(params).then(response => {
                  this.addTeam()
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        } else {
          this.$message({
            message: '该团队不存在',
            type: 'warning'
          })
        }
      },
      submitBillForm(formName) {
        const params = {
          isTender: 1,
          billId: this.billRow.billId,
          projectId: this.billRow.projectId,
          teamId: this.billRow.teamId,
          partyA: this.billRow.partyA,
          costAmount: this.billRow.costAmount,
          costTime: this.billRow.costTime,
          payer: this.billRow.payer,
          balance: this.billRow.balance
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            updateCost(params).then(response => {
              console.log(response)
              this.outerBillVisible = false
              this.fetchData()
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          billId: scope.row.billId,
          teamId: scope.row.teamId,
          dateCreated: scope.row.dateCreated,
          billAmount: scope.row.billAmount,
          isDel: 1
        }
        deleteTenderCompensation(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      receivingUnitChange(event) {
        let obj = {}
        obj = this.global.billUnitList.find(function(item) {
          return item.value === event
        })
        this.$set(this.teamRow, 'receivingUnitName', obj.label)
      },
      querySearchTeam(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.teamId
        const params = {
          teamName: queryString
        }
        selectTeam(params).then(response => {
          for (const i of response.responseBody) {
            i.value = i.teamName
          }
          let teamList = response.responseBody
          if (teamList.length === 0) {
            teamList = [{ value: '暂无数据' }]
          }
          callback(teamList)
        })
      },
      handleSelectTeam(item) {
        this.$set(this.teamRow, 'teamId', item.teamId)
      },
      querySearchProject(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        delete this.teamRow.tenderId
        if (queryString) {
          const params = {
            tenderName: queryString
          }
          selectProjectName(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.tenderName
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      },
      handleSelectProject(item) {
        this.$set(this.teamRow, 'tenderId', item.tenderId)
        this.$set(this.teamRow, 'tenderName', item.tenderName)
        this.$set(this.teamRow, 'teamId', item.teamId)
        this.$set(this.teamRow, 'teamName', item.teamName)
        this.$set(this.teamRow, 'partyA', item.partyA)
      },
      querySearchOperator(queryString, callback) {
        // queryString 为在框中输入的值
        // callback 回调函数,将处理好的数据推回
        if (queryString) {
          const params = {
            name: queryString,
            teamId: this.billRow.teamId
          }
          selectOperator(params).then(response => {
            for (const i of response.responseBody) {
              i.value = i.name
            }
            let projectList = response.responseBody
            if (projectList.length === 0) {
              projectList = [{ value: '暂无数据' }]
            }
            callback(projectList)
          })
        } else {
          callback([])
        }
      }
    },
    mounted() {
    },
    watch: {
      'outerVisible': {
        handler(newValue, oldValue) {
          this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
          if (this.$refs['teamRow']) {
            this.$refs['teamRow'].resetFields()
          }
          this.$set(this.teamRow, 'teamId', this.teamId)
          this.$set(this.teamRow, 'teamName', this.teamName)
        },
        immediate: true
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .dialog-footer {
    text-align: right;
  }

</style>


<style rel="stylesheet/scss" lang="scss">

</style>
